import React from 'react';
import { View, Image, ScrollView, StatusBar, NativeModules } from 'react-native';
import RNFS from 'react-native-fs';
import Share from 'react-native-share'
import { Lt, Color, Nav, Label, Jpp, Jx, Dialog, Images, cSys } from "../_utils";
import { ViewGoodsContentForShare } from './Goods';
import { ShareAlbum } from './ShareAlbum';
import { ShareContent } from './ShareContent';
import { ViewShare, ViewShares } from '../ViewShares';
import { cShareInfo, SHARE_MULTI, SHARE_SAVE, cShare } from '../_share';
import { eShare } from '../_util';


export class ShareTo extends React.PureComponent{
    constructor(props){
        super(props);

        this.params = this.props.navigation.state.params;
        const { images } = this.params;
        
        this.state = {
            selectsCount : 0,
        }

        cSys.checkWechatInstalled();
        cSys.checkQQInstalled();
        cSys.promiseCapturePermission(true);
        
        this.selectIdx = -1;

        this.shots = images.map(v=>cShareInfo.empty());
        this.albumRef = null;
        this.info = new cShareInfo;

        this.onAlbumRef = this.onAlbumRef.bind(this);
        this.onShotCombine = this.onShotCombine.bind(this);

        // this.onReady = this.onReady.bind(this);
        this.onShotSingle = this.onShotSingle.bind(this);
        this.onSelect = this.onSelect.bind(this);

        this.onSave = this.onSave.bind(this);
        this.onShare = this.onShare.bind(this);
    }
    static navigationOptions = {
        ...Nav.options,
        headerTitle: "分享",
    }
    componentDidMount(){
        if(Jpp.isAndroid){
            StatusBar.setTranslucent(false);
        }
        // this.params.isFromDetail
        if(Jpp.isAndroid && this.params.eshare == eShare.detail){
            Dialog.loading(true);
            setTimeout(()=>{
                Dialog.hiding();
            }, 6000);
        }
    }
    componentWillUnmount(){
        // this.params.isFromDetail
        if(Jpp.isAndroid && this.params.eshare == eShare.detail){
            StatusBar.setTranslucent(true);
        }
        // StatusBar.setHidden(false);
    }
    onAlbumRef(ref){
        this.albumRef = ref;
    }
    onShotCombine(i, image){
        this.shots[i].imageShot = image;
        if(Jpp.isAndroid){
            Dialog.hiding();
        }
    }
    onShotSingle(shot){
        // console.warn(this.selectIdx + ": " + Jx.stringify(shot));
        this.shots[this.selectIdx] = shot;
    }
    toInfo(i, shotRef, onShotSingle){
        // isCombine, isFromDetail
        const { images, data, datas, eshare} = this.params;
        return {
            // datas || (isCombine && i == 0 && data),
            isCapture : (eshare == eShare.hotdaily) || (eshare == eShare.detail && i == 0 && data),
            imageOri : images[i],
            shotRef,
            shot : this.shots[i],
            // onReady : this.onReady,
            onShot : onShotSingle || this.onShotSingle,
        }
    }
    onSelect(params){
        let i = params.index;
        let selectsCount = params.selectsCount;
        this.setState({selectsCount});
        if(selectsCount == 1){
            this.selectIdx = i;
            // console.warn(i + ": " + Jx.stringify(target));
            this.info.init(this.toInfo(i, params.ref))
        }
        return;
        if(params.ref){
            let info = new cShareInfo;
            info.init(this.toInfo(i, params.ref, shot=>this.shots[i]=shot));
            info.promiseConfig({});
        }
    }

    onShare(){
        const selects = this.albumRef.getSelects().map(v=>{
            let info = new cShareInfo;
            info.init(this.toInfo(v.index, v.ref, shot=>this.shots[v.index]=shot));
            // return info.promiseImage({SHARE_MULTI});
            if(Jpp.isIOS){
                return info.promiseImage({SHARE_MULTI});
            }
            return new Promise(resolve=>{
                info.promiseImage({SHARE_MULTI}).then(image=>{
                    if(image){
                        // console.warn("copyFrom: " + image);
                        // "file://" + 
                        let file = RNFS.ExternalCachesDirectoryPath + "/" + v.index + '.jpg';
                        // console.warn("copyTo: " + file);
                        RNFS.copyFile(image, file, ).then(()=>{
                            // console.warn("copySuccess: " + file);
                            resolve(file);
                            return;
                            NativeModules.uModules.getContentUri(file)
                            .then(r=>{
                                if(r){
                                    resolve(r);
                                }else{
                                    resolve(false);
                                }
                            }).catch(err=>{
                                resolve(false);
                            })
                        }).catch(err=>{
                            // console.warn("copyFail: " + file);
                            resolve(false);
                        });
                    }else {
                        resolve(false);
                    }
                }).catch(err=>{
                    resolve(false);
                })
            });
        });
        Dialog.retain(true);
        Promise.all(
            selects
        ).then(urls=>{
            // urls = urls.map(v=>{
            //     if(v.toLowerCase().includes('file://')){
            //         return v.substr(7);
            //     }
            //     return v;
            // })
            console.warn(Jx.stringify(urls));
            Dialog.release();
            if(Jpp.isAndroid){
                NativeModules.uModules.shareImages(urls);
            }else {
                Share.open({
                    // 安卓会自己获取本地文件后缀
                    // type : 'image/jpeg',
                    urls,
                }).catch(err=>null);
            }
        }).catch(err=>{
            Dialog.toast("分享失效");
            Dialog.release();
        })
    }

    onSave(){
        const selects = this.albumRef.getSelects().map(v=>{
            let info = new cShareInfo;
            info.init(this.toInfo(v.index, v.ref, shot=>this.shots[v.index]=shot));
            return new Promise(resolve=>{
                info.promiseImage({SHARE_SAVE}).then(image=>{
                    if(image){
                        cSys.toCameraRoll(image).then(r=>{
                            resolve(r);
                        }).catch(err=>{
                            resolve(false);
                        })
                    }else {
                        resolve(false);
                    }
                }).catch(err=>{
                    resolve(false);
                })
            });
        });
        Dialog.retain(true);
        Promise.all(
            selects
        ).then(urls=>{
            console.warn(Jx.stringify(urls));
            Dialog.release();
            Dialog.toast("图片已保存");
            return;
            Promise.all(urls.map(v=>{
                NativeModules.uModules.getFilenameFromContentUri(v)
            }))
            .then(rs=>{
                console.warn(Jx.stringify(rs));
            })
        }).catch(err=>{
            Dialog.release();
            Dialog.toast("保存失败");
        })
    }
    render(){
        // isCombine, isFromDetail
        const { images, data, datas, eshare } = this.params;
        const { selectsCount } = this.state;
        return <View style = {{flex:1}}>
        <Nav.StatusBar/>
        <View style={{flex:1, backgroundColor:"white", justifyContent:"space-between"}}><ScrollView><View>
            <Label style={{fontSize:Lt.c18, color:Color.c3, marginLeft:Lt.margin, marginTop:20,}}>选择分享图片</Label>
            <ShareAlbum 
                // isCombine = {isCombine}
                eshare = { eshare }
                images = {images} 
                data = {data} 
                datas = {datas}
                ref={this.onAlbumRef} 
                onSelect={this.onSelect}
                onShotCombine={this.onShotCombine}
            />
            {
                (eshare != eShare.detail) ? null : 
                <ViewGoodsContentForShare style={{marginHorizontal:Lt.margin}} data={data} />
            }
            <View style={{height:10, backgroundColor:Color.back, marginVertical:Lt.margin}}/>
            <ShareContent data={data}/>
        </View></ScrollView>
        {
            (selectsCount == 0) ? null : ((selectsCount == 1) ? 
            <ViewShares
                info = {this.info}
            /> : 
            <View style={{height:120, flexDirection:"row", justifyContent:"space-around", alignItems:"center"}}>
                <ViewShare onPress={this.onShare} source={Images.fenxiang_qd}>{"分享" + (Jpp.isAndroid ? "至" : "微信") + "QQ" }</ViewShare>
                <ViewShare onPress={this.onSave} source={Images.shouji}>保存至本地</ViewShare>
            </View>)
        }
        </View></View>;
    }
}